package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.holders.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:uid";

    public void addCart(Cart cart) {
        // 1.获取用户
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + id;
        // 2.获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 3.判断商品是否存在
        String skuId = cart.getSkuId().toString();
        Boolean exists = hashOps.hasKey(skuId);
        if (BooleanUtils.isTrue(exists)) {
            // 4.存在，修改数量
            // 4.1.取出缓存中的cart
            String json = hashOps.get(skuId);
            Cart cacheCart = JsonUtils.toBean(json, Cart.class);
            // 4.2.修改数量
            cacheCart.setNum(cacheCart.getNum() + cart.getNum());
            // 4.3.写回redis
            hashOps.put(skuId, JsonUtils.toString(cacheCart));
        } else {
            // 5.不存在，直接添加
            hashOps.put(skuId, JsonUtils.toString(cart));
        }
    }

    public List<Cart> queryCartList() {
        // 1.获取用户
        Long id = UserHolder.getUser().getId();
        String key = KEY_PREFIX + id;

        Boolean exits = redisTemplate.hasKey(key);
        if (BooleanUtils.isFalse(exits)) {
            // 用户不存在，购物车没有
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        // 2.获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 3.获取所有的value
        List<String> values = hashOps.values();
        if (CollectionUtils.isEmpty(values)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        return values.stream()
                .map(json -> JsonUtils.toBean(json, Cart.class))
                .collect(Collectors.toList());
    }
}
